/*
 * 滚动动画mixins
 * @Author: ljb
 * @Date: 2018-11-14 15:11:15
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-12-26 10:13:41
 */
export default {
	name: 'easeScroll',
	methods: {
		/**
         * 滑动动画
         * @param  {Number} ex {滑动结束的x值，默认为0}
         * @param  {Number} ey {滑动结束的y值，默认为0}
         * @param  {Number} speed {滑动的速度反比，值越大滑动越慢}
         * @param  {Boolean} is_limited {是否限制结束的x，y值}
         * @return {undefined}
         */
		easeScrollTo(ex = 0, ey = 0, speed = 0.4, is_limited = true) {
			if (speed >= 1)speed = 0.9;

			if (is_limited) {
				[ex, ey] = this.limitDestination(ex, ey);
			}

			const frame = requestAnimationFrame(() => {
				const sx = window.scrollX;
				const sy = window.scrollY;

				let x_desc = (sx - ex) * speed;
				let y_desc = (sy - ey) * speed;

				x_desc = x_desc > 0 ? Math.floor(x_desc) : Math.ceil(x_desc);
				y_desc = y_desc > 0 ? Math.floor(y_desc) : Math.ceil(y_desc);

				const frame_dest_x = ex + x_desc;
				const frame_dest_y = ey + y_desc;

				if (Math.abs(ey - sy) <= 2 &&
                    Math.abs(ex - sx) <= 2
				) {
					window.scrollTo(ex, ey);
					cancelAnimationFrame(frame);
				} else {
					window.scrollTo(frame_dest_x, frame_dest_y);
					this.easeScrollTo(ex, ey, speed);
				}
			});
		},

		/**
         * 限制结束处的x值和y值
         * @param  {Number} ex {滚动结束时的x值}
         * @param  {Number} ey {滚动结束时的y值}
         * @return {Array} {滚动结束时的x，y值组成的数组}
         */
		limitDestination(ex, ey) {
			if (ex < 0) ex = 0;
			if (ey < 0) ey = 0;

			if (ex > document.body.scrollWidth - window.innerWidth) {
				ex = document.body.scrollWidth - window.innerWidth;
			}
			if (ey > document.body.scrollHeight - window.innerHeight) {
				ey = document.body.scrollHeight - window.innerHeight;
			}

			return [ex, ey];
		},
	},
};

